<template>
  <!-- 外访案件管理-团队案件池-页面 -->
  <section class="page visit-team-case-manage">
    <data-form :model="model" :page="pageService" :rules="rules" @handleResetForm="follFeedback" @onSearch="refreshData">
      <template slot="inputs">
        <el-form-item label="订单编号" prop="caseNumber">
          <el-input v-model="model.caseNumber"></el-input>
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="model.batchNumber"></el-input>
        </el-form-item>
        <el-form-item label="委托方" prop="principalId">
          <el-select v-model="model.principalId" placeholder="请选择" clearable>
            <el-option v-for="{index,name,id} in principalList.content" :key="index" :label="name" :value="id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户姓名" prop="personalName">
          <el-input v-model="model.personalName"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="model.idCard"></el-input>
        </el-form-item>
        <el-form-item label="放款日期" prop="loanDate">
          <el-date-picker type="daterange" :editable="false" v-model="model.loanDate" placeholder="选择日期时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号" prop="mobileNo">
          <el-input v-model="model.mobileNo"></el-input>
        </el-form-item>
        <el-form-item label="业务团队" prop="partnerName">
          <el-input v-model="model.partnerName"></el-input>
        </el-form-item>
        <el-form-item label="机构" prop="deptId">
          <select-department v-model="model.deptId" @on-select-change="(id, code) => departemntChange(id, code)"></select-department>
        </el-form-item>
        <el-form-item label="催收员" prop="currentCollectorRealName">
          <el-input v-model="model.currentCollectorRealName"></el-input>
        </el-form-item>
        <el-form-item label="部门催收剩余天数" prop="partCollectionRemainingDays">
          <number-range v-model="model.partCollectionRemainingDays" :isInteger="true"></number-range>
        </el-form-item>
        <el-form-item label="个人催收剩余天数" prop="personalCollectionRemainingDays">
          <number-range v-model="model.personalCollectionRemainingDays" :isInteger="true"></number-range>
        </el-form-item>
        <el-form-item label="贷款银行" prop="bankName">
          <el-input v-model="model.bankName"></el-input>
        </el-form-item>
        <el-form-item label="催收总金额" prop="overdueAmount">
          <number-range v-model="model.overdueAmount"></number-range>
        </el-form-item>
        <el-form-item label="业务承接地" prop="businessAddress">
          <el-input v-model="model.businessAddress"></el-input>
        </el-form-item>
        <el-form-item label="上牌地" prop="boardAddress">
          <el-input v-model="model.boardAddress"></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="carNo">
          <el-input v-model="model.carNo"></el-input>
        </el-form-item>
        <el-form-item label="案件来源" prop="dataFromSource">
          <el-select v-model="model.dataFromSource" placeholder="请选择" clearable>
            <el-option v-for="{index,name,code} in $dict.getDictData('DataFromSource')" :key="index" :label="name" :value="code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="案件流入时间" prop="followInTime">
          <el-date-picker type="datetimerange" :editable="false" v-model="model.followInTime" placeholder="选择日期时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="案件标记" prop="caseMark">
          <el-select v-model="model.caseMark" placeholder="请选择" clearable>
            <el-option v-for="{index,name,code} in $dict.getDictData('CaseMark')" :key="index" :label="name" :value="code"></el-option>
          </el-select>
        </el-form-item>
      </template>
    </data-form>
    <data-box :data="dataSet" :page="pageService" :selectionList.sync="selectionList" :sort="sortService" @onPageChange="queryPageInfo" ref="data-box" showCaseMark>
      <template slot="buttons">
        <el-button @click="manualDivision" v-auth="611">重新分案</el-button>
        <template>
          <el-button @click="applyClick(item)" v-for="(item,index) in applyComponent" :key="index" v-auth="item.auth">{{item.name}}</el-button>
        </template>
        <el-button @click="dealManualPartReturnCase" v-auth="270">委托方回收</el-button>
      </template>
      <template slot="append">
        <case-marker :selectionList="selectionList" @change-color="onColorChange"></case-marker>
      </template>
      <template slot="columns">
        <el-table-column :min-width="$helper.getColumnWidth(6)" label="订单编号" prop="caseNumber">
          <template slot-scope="scope">
            <el-button @click="openExecutionPage(scope.row)" type="text">{{ scope.row.caseNumber }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="batchNumber" label="批次号" :min-width="$helper.getColumnWidth(6)">
        </el-table-column>
        <el-table-column prop="principalName" label="委托方" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="personalName" label="客户姓名" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="idCard" label="身份证号" :min-width="$helper.getColumnWidth(6)">
        </el-table-column>
        <el-table-column prop="loanDate" label="放款日期" :formatter="(row) => $filter.dateFormat(row.loanDate)" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
        <el-table-column prop="mobileNo" label="手机号" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="partnerName" label="业务团队" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="bankName" label="贷款银行" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="partCollectionRemainingDays" label="部门催收剩余天数" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="personalCollectionRemainingDays" label="个人催收剩余天数" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="deptName" label="机构" show-overflow-tooltip :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="currentCollectorRealName" label="催收员" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="leaveCaseFlag" label="留案标识" :min-width="$helper.getColumnWidth(3)" :formatter="(row) => $filter.dictConvert(row.leaveCaseFlag,'CommonFlag')">
        </el-table-column>
        <el-table-column prop="leaveDueDate" label="留案到期日期" :min-width="$helper.getColumnWidth(5)" :formatter="(row) => $filter.dateFormat(row.leaveDueDate)">
        </el-table-column>
        <el-table-column prop="telAssistflag" label="电催协催标识" :min-width="$helper.getColumnWidth(3)" :formatter="(row) => $filter.dictConvert(row.telAssistflag,'CommonFlag')">
        </el-table-column>
        <el-table-column prop="legalAssistFlag" label="法务协催标识" :min-width="$helper.getColumnWidth(3)" :formatter="(row) => $filter.dictConvert(row.legalAssistFlag,'CommonFlag')">
        </el-table-column>
        <el-table-column prop="riskFlag" label="风险客户标识" :min-width="$helper.getColumnWidth(3)" :formatter="(row) => $filter.dictConvert(row.riskFlag,'CommonFlag')">
        </el-table-column>
        <el-table-column prop="loanAmount" label="贷款金额" :min-width="$helper.getColumnWidth(4)" :formatter="(row) =>  $filter.toThousands(row.loanAmount)">
        </el-table-column>
        <el-table-column prop="loanPeriod" label="贷款期数" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="overdueStage" label="逾期阶段" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="overdueDays" label="逾期天数" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="overdueAmount" label="催收总金额" :min-width="$helper.getColumnWidth(6)" :formatter="(row) =>  $filter.toThousands(row.overdueAmount)">
        </el-table-column>
        <el-table-column prop="businessAddress" label="业务承接地" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="boardAddress" label="上牌地" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="carNo" label="车牌号" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="gpsAmount" label="gps个数" :min-width="$helper.getColumnWidth(3)">
        </el-table-column>
        <el-table-column prop="dataFromSource" label="案件来源" :formatter="(row) => $filter.dictConvert(row.dataFromSource,'DataFromSource')" :min-width="$helper.getColumnWidth(4)">
        </el-table-column>
        <el-table-column prop="followInTime" label="案件流入时间" :formatter="(row) => $filter.dateTimeFormat(row.followInTime)" :min-width="$helper.getColumnWidth(5)">
        </el-table-column>
      </template>
      <p slot="footer">{{`查询结果统计：列表欠款总金额 ${$filter.toThousands(totalInfo.totalAmount)}元`}}</p>
    </data-box>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" :visible.sync="dialog.ManualDivision" title="重新分案" width="800px" @open="$nextTick(()=>$refs['case-allot'].refreshDept())">
      <case-allot :fromChannel="caseChannel" @close="dialog.ManualDivision=false" @refreshList="refreshData" again ref="case-allot"></case-allot>
    </el-dialog>

    <!-- 申请 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" :title="`${applyType.name}申请`" :visible.sync="dialog.applyDialog" width="800px">
      <component :is="isComponent" :applyType="applyType.value" :caseIds="selectedCaseIds" :otherData="otherModel" :fromChannel="caseChannel" @close="dialog.applyDialog = false;refreshData();">
      </component>
    </el-dialog>

    <!-- 还款弹窗 -->
    <el-dialog :center="true" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" :visible.sync="dialog.repayment" @open="$nextTick(()=>$refs['team-case-repayment'].update(teamCaseObj))" title="还款" width="400px">
      <team-case-repayment @close="refreshData();dialog.repayment=false;teamCaseObj={}" ref="team-case-repayment"></team-case-repayment>
    </el-dialog>

    <!-- 批量还款弹窗 -->
    <el-dialog :center="true" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" :visible.sync="dialog.batchRepayment" @open="$nextTick(()=>$refs['team-case-batch-repayment'].updateList(selectCaseList))" title="批量还款" width="800px">
      <team-case-batch-repayment @close="dialogClose" ref="team-case-batch-repayment"></team-case-batch-repayment>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" title="委托方回收" :visible.sync="dialog.principalRecovery" width="400px">
      <principal-recovery :ids="selectedCaseIds" @close="dialog.principalRecovery = false;refreshData();" />
    </el-dialog>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies, Layout, Auth } from "~/core/decorator";
import { PageService } from "~/utils/page.service";
import { SortService } from "~/utils/sort.service";
import NumberRange from "~/components/common/number-range.vue";
import CaseMarker from "~/components/common/case-marker.vue";
import { Getter, Mutation, State, namespace } from "vuex-class";
import { CaseInfoService } from "~/services/domain-service/case-info.service";
import { VisitCaseManageService } from "~/services/domain-service/visit-case-manage.service";
import { CaseApplyRecordService } from "~/services/domain-service/case-apply-record.service";
import CaseAllot from "~/components/distribution-common/case-allot.vue";
import {
  ApplyType,
  CASE_CHANNEL,
  CASE_HALT_CATEGORY,
  MENU_CHANNEL
} from "~/config/enum.config";
import GetLabelName from "~/components/labeling-strategy/get-label-name.vue";
import TeamCaseRepayment from "~/components/visit-case/team-case-repayment.vue";
import TeamCaseBatchRepayment from "~/components/visit-case/team-case-batch-repayment.vue";
import RobberyApply from '~/components/apply-component/robbery-apply.vue'
import TurnSourceApply from "~/components/apply-component/turn-source-apply.vue"
import PauseApply from "~/components/apply-component/pause-apply.vue"
import LeaveCaseApply from "~/components/apply-component/leave-case-apply.vue"
import SelectDepartment from "~/components/business-component/select-department.vue";
import PrincipalRecovery from "~/components/apply-component/principal-recovery.vue";

const AllotModule = namespace("case-allot");
@Auth(603)
@Layout("workspace")
@Component({
  components: {
    GetLabelName,
    NumberRange,
    CaseMarker,
    CaseAllot,
    TeamCaseRepayment,
    TeamCaseBatchRepayment,
    RobberyApply,
    TurnSourceApply,
    PauseApply,
    LeaveCaseApply,
    SelectDepartment,
    PrincipalRecovery
  }
})
export default class VisitTeamCaseManage extends Vue {
  @Dependencies(PageService)
  private pageService: PageService;
  @Dependencies(SortService)
  private sortService: SortService;
  @Dependencies(VisitCaseManageService)
  private visitCaseManageService: VisitCaseManageService;
  @Dependencies(CaseApplyRecordService)
  private CaseApplyRecordService: CaseApplyRecordService;
  @Dependencies(CaseInfoService)
  private caseInfoService: CaseInfoService;
  @Mutation
  private updateCollectionType;
  @Getter
  private visitDepartmentData;
  @AllotModule.Mutation private updateCaseIds;
  @State private principalList: any;

  private model: any = {
    caseNumber: "",
    personalName: "",
    mobileNo: "",
    idCard: "",
    overdueAmount: {
      max: "",
      min: ""
    },
    loanDate: [],
    principalId: '',
    partCollectionRemainingDays: { min: '', max: '' },
    personalCollectionRemainingDays: { min: '', max: '' },
    bankName: '',
    businessAddress: '',
    boardAddress: '',
    carNo: '',
    dataFromSource: '',
    followInTime: [],
    deptId: '',
    currentCollectorRealName: '',
    partnerName: '',
    batchNumber: '',
    caseMark: ''
  };
  private dialog = {
    ManualDivision: false,
    apply: false,
    repayment: false,
    batchRepayment: false,
    applyDialog: false,
    principalRecovery: false
  };
  private rules: any = {};
  private dataSet: any[] = [];
  private selectionList: any[] = [];
  private caseMark: any = "";
  private applyFlowCase: any = {};
  private applyType: any = {};
  private caseChannel = CASE_CHANNEL.visit;
  private otherModel: any = {
    caseHaltCategory: CASE_HALT_CATEGORY.CASE_HALT
  };
  private totalInfo: any = {};
  private teamCaseObj: any = {};
  private selectCaseList: any = [];
  private isComponent: string = ''

  private applyComponent: any = [
    {
      name: '申请流转',
      component: 'turn-source-apply',
      applyType: ApplyType.turn,
      auth: 612
    },
    {
      name: '申请停催',
      component: 'pause-apply',
      applyType: ApplyType.pause,
      auth: 613
    },
    {
      name: '申请留案',
      component: 'leave-case-apply',
      applyType: ApplyType.leave,
      auth: 614
    },
    {
      name: '回收案件',
      component: 'robbery-apply',
      applyType: ApplyType.recycle,
      auth: 615
    },
  ]

  private mounted() {
    this.refreshData();
  }

  private activated() {
    this.refreshData();
  }

  private departemntChange(id, code) { }


  private queryTotalInfo() {
    this.visitCaseManageService
      .visitTeamCasePoolAmount(this.paramsHandler())
      .subscribe(data => (this.totalInfo = data));
  }

  private queryPageInfo() {
    this.visitCaseManageService
      .visitTeamCasePool(this.paramsHandler(), this.pageService)
      .subscribe(data => {
        this.dataSet = data;
        this.selectionList = [];
      });
  }

  /**
   * 查询案件
   */
  private refreshData() {
    this.queryTotalInfo();
    this.queryPageInfo();
  }


  private paramsHandler() {
    const params = { ...this.model }
    params.overdueAmountMax = this.model.overdueAmount ? this.model.overdueAmount.max : ""
    params.overdueAmountMin = this.model.overdueAmount ? this.model.overdueAmount.min : ""
    params.partCollectionRemainingDaysMax = params.partCollectionRemainingDays ? this.model.partCollectionRemainingDays.max : ""
    params.partCollectionRemainingDaysMin = params.partCollectionRemainingDays ? this.model.partCollectionRemainingDays.min : ""
    params.personalCollectionRemainingDaysMax = params.personalCollectionRemainingDays ? this.model.personalCollectionRemainingDays.max : ""
    params.personalCollectionRemainingDaysMin = params.personalCollectionRemainingDays ? this.model.personalCollectionRemainingDays.min : ""
    params.followInTimeMin = this.model.followInTime.length ? this.$filter.dateTimeFormat(this.model.followInTime[0]) : ''
    params.followInTimeMax = this.model.followInTime.length ? this.$filter.dateTimeFormat(this.model.followInTime[1]) : ''
    params.loanDateMin = this.$filter.dateRanageFormat(this.model.loanDate).start
    params.loanDateMax = this.$filter.dateRanageFormat(this.model.loanDate).end

    delete params.overdueAmount
    delete params.partCollectionRemainingDays
    delete params.personalCollectionRemainingDays
    delete params.followInTime
    delete params.loanDate

    return params
  }


  /**
   * 进入查看执行页
   */
  private openExecutionPage(row) {
    this.$router.openCaseDetail(row.id, {
      menuChannel: MENU_CHANNEL.Visit_team,
      otherData: {
        data: this.model,
        page: this.pageService,
        sort: this.sortService
      }
    });
  }

  /**
   * 重置dataRange
   */
  private follFeedback() {
    this.model.overdueAmount = { min: "", max: "" };
    this.model.partCollectionRemainingDays = { min: '', max: '' }
    this.model.personalCollectionRemainingDays = { min: '', max: "" }
  }

  /**
   * 手动分案
   */
  private manualDivision() {
    if (this.selectionList.length === 0) {
      this.$message.info("请选择要分配的案件");
      return;
    }
    this.updateCaseIds(this.selectionList.map(v => v.id));
    this.dialog.ManualDivision = true;
  }

  /**
   * 申请
   */
  private async applyClick(item) {
    this.applyType = item.applyType;
    if (this.selectionList.length === 0) {
      this.$message(`请选择要${this.applyType.name}的案件`);
      return;
    }
    this.isComponent = item.component
    this.dialog.applyDialog = true
  }

  private get selectedCaseIds() {
    return this.selectionList.map(v => v.id);
  }

  private onColorChange(val) {
    const colorModel: any = {
      caseIds: this.selectionList.map(v => v.id),
      caseMark: val
    };
    this.caseInfoService
      .caseInfoMarkColor(colorModel)
      .subscribe(this.refreshData);
  }

  private onApplyClose() {
    this.dialog.apply = false;
    // 重置其他数据
    this.otherModel = {};
    this.refreshData();
  }

  /**
   * 还款
   */

  private repaymentClick(row) {
    this.dialog.repayment = true;
    this.teamCaseObj = row;
  }
  /**
   * 批量还款
   */

  private batchRepaymentClick() {
    if (this.selectionList.length !== 0) {
      this.dialog.batchRepayment = true;
      this.selectCaseList = this.selectionList;
    } else {
      this.$message(`请选择要批量还款的案件`);
    }
  }
  /**
   * 批量还款弹窗关闭回调
   */
  private dialogClose() {
    this.refreshData();
    this.dialog.batchRepayment = false;
    this.selectionList = [];
  }
  /**
   * 委托方回收
   */
  private dealManualPartReturnCase() {
    if (this.selectionList.length !== 0) {
      this.dialog.principalRecovery = true;
    } else {
      this.$message(`请选择要进行委托方回收的案件`);
    }
  }
}
</script>

<style lang="less" scoped>
</style>
